import { useEffect } from 'react'
import { Button, Space, message } from 'antd'
import { useRoutes, useLocation, useNavigate } from 'react-router-dom'
import router from "./router"

const ToLogin = () => {
  const navigateTo = useNavigate()
  useEffect(() => {
    // 加载完组件之后执行这里的代码
    navigateTo("/login")
    message.warning("您还没有登录，请登录后再访问！")
  }, [])
  return <div></div>
}

// 建立 路由守卫
const BeforeRouterEnter = () => {
  const outlet = useRoutes(router)
  const location = useLocation()
  let token = localStorage.getItem('token')
  // 未登录则跳转登录页
  if (!token && location.pathname != '/login') {
    // 这里不能直接用 useNavigate 来实现跳转 ，因为需要BeforeRouterEnter是一个正常的JSX组件
    return <ToLogin />
  }

  return outlet
}

function App() {
  return (
    <div className="App">
      <BeforeRouterEnter />
    </div>
  )
}

export default App
